<template>
  <view class="wrap">
    <view class="conts">
      <view class="content">
        <block v-if="lists.length > 0">
          <view class="item" v-for="(item, index) in sthList" :key="index">
            <view class="item_info">
              <view class="radio" @click="handleSelect(item)">
                <radio color="#E1222A" :checked="item.isselect"/>
              </view>
              <view class="info">
                <view class="img_wrap">
                  <image :src="item.image" mode="aspectFill"></image>
                </view>
                <view class="detail">
                  <view class="title">{{ item.name }}</view>
                  <view class="price" style="display: flex;">
                    <text>价格: {{ item.price }}</text>
                    <view class="poolNum" style="display: flex; margin: 20rpx; align-items: center;">
                      <button @click="decrementQuantity(item)">-</button>
                      <input :value="item.number" type="number" min="0" @change="updateQuantity($event, item)" style="width: 80rpx; text-align: center;  margin: 0 10rpx;" />
                      <button @click="incrementQuantity(item)">+</button>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </block>
        <view class="empty" v-else>
          <u-empty></u-empty>
        </view>
      </view>
      <view class="bottom">
        <view class="radio" @click="handleAllSelect">
          <radio color="#E1222A" :checked="allSelect"/>
          <text>全选</text>
        </view>
        <view class="total" v-if="!del">
          <text>共：</text> 
          <text class="quantity">{{ total_quantity }}件</text>
        </view>
        <view class="btn" v-if="!del" @click="toSubmit">去提货</view>
        <view class="btn" v-else @click="handleDel">删除</view>
      </view>
    </view>
  </view>
</template>

<script>
import { cartList, delCart, preOrder, getSthList,sumbitAdmin } from '@/api/index.js';

export default {
  data() {
    return {
      lists: [],
      allSelect: false,
      activeList: [],
      page: 1,
      last_page: null,
      del: false,
      sthList: [], // 提货列表
	  sthId:'' ,//用于提交提货 
	  submitting: false, // 新增：跟踪提交状态
	  number:0
    };
  },

  computed: {
    total_quantity() {
      let quantity = 0;
      this.activeList.forEach(item => {
        quantity += item.number; // 累加每个商品的数量
      });
      return quantity;
    }
  },

  onShow() {
    this.getData();
    this.getList(); // 提货列表
  },

  onReachBottom() {
    if (this.page === this.last_page) {
      uni.showToast({
        title: '已经是最后一页了',
        icon: 'none'
      });
    } else {
      this.page++;
      this.getData();
    }
  },

  methods: {
    async getData() {
      if (this.page === 1) {
        this.lists = [];
        this.allSelect = false;
        this.activeList = [];
      }
      const res = await cartList({ page: this.page });
      res.data.data.forEach(item => {
        item.isselect = false; // 确保每个商品都有 isselect 属性，默认为 false
        item.number = item.number || 0; // 初始化数量为0或已有值
        this.lists.push(item);
      });
      this.last_page = res.data.last_page;
    },

    async getList() {
      const res = await getSthList();
      this.sthList = res.data;
      console.log('ids', this.sthList);

      // 确保每个商品项都有 isselect 和 number 属性
      this.sthList.forEach(item => {
        item.isselect = false;
        item.number = item.number || 0; // 初始化数量为0或已有值
      });
    },

    handleEdit() {
      this.sthList.forEach(item => {
        item.isselect = false;
      });
      this.del = true;
      this.allSelect = false;
      this.activeList = [];
    },

    handleSelect(item) {
        // 切换选中状态
        item.isselect = !item.isselect;
        
    
        // 如果选中并且数量为0，则设置为1
        if (item.isselect && item.number === undefined || item.number === 0) {
          item.number = 1;
        }
    
        // 如果取消选中，则设置数量为0
        if (!item.isselect) {
          item.number = 0;
        }
    
        // 更新 allSelect 状态
        this.allSelect = this.sthList.every(i => i.isselect);
    
        // 更新 activeList
        this.activeList = this.sthList.filter(i => i.isselect);
    
        // 更新 activeList 中的商品数量
        this.updateActiveList(item);
      },

    handleAllSelect() {
      this.allSelect = !this.allSelect;
    
      // 统一设置所有商品的 isselect 属性
      this.sthList.forEach(item => {
        item.isselect = this.allSelect;
    
        if (this.allSelect) {
          // 如果全选，则确保数量至少为1
          if (item.number === 0) {
            item.number = 1;
          }
        } else {
          // 如果取消全选，则取消选中状态并清空数量
          item.isselect = false;
          item.number = 0;
        }
      });
    
      // 更新 activeList
      this.activeList = this.allSelect ? [...this.sthList] : [];
    },

    handleDel() {
      // if (this.activeList.length <= 0) {
      //   uni.$u.toast('请选择要删除的商品');
      //   return;
      // }
      const params = this.activeList.map(item => item.id).join(',');
      delCart({ ids: params }).then(res => {
        uni.$u.toast(res.msg);
        setTimeout(() => {
          this.page = 1;
          this.getData();
        }, 1200);
      });
    },

    handleComplete() {
      this.sthList.forEach(item => {
        item.isselect = false;
		item.number = 0; 
      });
      this.del = false;
      this.allSelect = false;
      this.activeList = [];
    },

    async handlePay() {
      uni.redirectTo({
        url: "/pageC/takeRecords"
      });
    },

    incrementQuantity(item) {
        // 检查是否选中，如果未选中则自动选中
        if (!item.isselect) {
          this.handleSelect(item); // 自动选中商品并设置数量为1
          return; // 直接返回，不进行额外的数量增加
        }
        // 增加数量
        item.number++;
        this.updateActiveList(item);
      },

    decrementQuantity(item) {
		if (item.isselect === undefined || item.isselect === false) {
		      this.handleSelect(item); // 自动选中商品
		    }
		console.log(item);
      if (item.number > 0) {
        item.number--;
        this.updateActiveList(item);
      }
	   if (item.number === 0 && item.isselect == true) {
	   //      uni.showToast({
	   //      	title:"提货数量不能少于0",
				// icon:'none'
	   //      }) 	
			item.isselect = false
	      }
    },

    updateActiveList(item) {
      const index = this.activeList.findIndex(i => i.id === item.id);
      if (index !== -1) {
        this.$set(this.activeList, index, item);
      }
    },

    updateQuantity(event, item) {
		console.log(event);
		console.log('item',item);
		// if (item.isselect == false) {
		// 		uni.showToast({
		// 		title: '请先选中商品',
		// 		icon: 'none'
		// 	});
		// // console.log(item.number);
		
		// console.log(222,this.sthList[0].number);
		// console.log(item.number);
		// return;
	 //  }
      const value = event.target.value;
      if (!isNaN(value)) {
        item.number = Math.max(0, value); // 数量不能小于0
        
        // 如果数量变为0，则取消选中状态
        if (item.number === 0) {
          this.handleSelect(item); // 调用 handleSelect 来取消选中状态
		  uni.showToast({
		  	title:"提货数量不能少于0",
			icon:'none'
		  })
        } else {
          this.updateActiveList(item);
        }
      }
    },
	 async toSubmit() {
	     this.submitting = true; // 设置提交状态为true
	 
	     // 初始化拼接字符串
	     let selectedItemsString = '';
	 
	     // 收集选中的商品及其数量并拼接成字符串
	     this.sthList.forEach((item, index) => {
	       if (item.isselect) {
	         selectedItemsString += `${item.id}-${item.number}`;
	         if (index < this.sthList.length - 1 && this.sthList[index + 1].isselect) {
	           selectedItemsString += '|'; // 使用'|'作为分隔符
	         }
	       }
	     });
	 // console.log(selectedItemsString);
	     // 如果没有任何选中的商品，提示用户
	     if (!selectedItemsString) {
	       uni.$u.toast('没有选择提货的商品');
	       this.submitting = false;
	       return;
	     }
	 
	     
	       // 调用API进行提交
	       const res = await sumbitAdmin({ data: selectedItemsString });
		   if(res.code == 1){
			   uni.$u.toast(res.msg);
			    setTimeout(() => {
				 uni.navigateBack();
			   }, 500);
		   }
		   if(res.code == 0 ){
			  // uni.$u.toast(res.msg);
			  // console.log(res.msg);
			  uni.showToast({
			  	title: res.msg,
			  	icon: 'none'
				
			  })
		   }
	       // 清空选中状态及数量
	       this.handleComplete();
	     
	   },
  }
};
</script>

<style lang="scss" scoped>
.wrap {
  min-height: 100vh;
  height: fit-content;
  background-color: #f6f6f6;
  box-sizing: border-box;

  .conts {
    position: relative;
    z-index: 1;
    padding: 0 0 168rpx;
    box-sizing: border-box;

    .content {
      padding: 24rpx;
      width: 100%;
      box-sizing: border-box;

      .item {
        padding: 24rpx;
        margin-bottom: 24rpx;
        border-radius: 12rpx;
        background-color: #fff;
        box-sizing: border-box;

        .item_info {
          width: 100%;
          display: flex;
          align-items: center;

          .info {
            flex: 1;
            width: 80%;
            height: 220rpx;
            display: flex;
            align-items: center;

            .img_wrap {
              width: 226rpx;
              height: 220rpx;
              margin: 0 16rpx 0 14rpx;
              border-radius: 16rpx;

              image {
                width: 100%;
                height: 100%;
                border-radius: 16rpx;
              }
            }

            .detail {
              width: calc(100% - 250rpx);
              height: 220rpx;
              display: flex;
              flex-direction: column;
              justify-content: space-between;

              .title {
                font-size: 30rpx;
                color: #232323;
                overflow: hidden;
                white-space: nowrap;
                text-overflow: ellipsis;
                word-break: break-all;
                margin-bottom: 16rpx;
              }

              .gui {
                font-size: 26rpx;
                color: #666666;
                flex: 1;
              }

              .price {
                display: flex;
                align-items: center;
                justify-content: space-between;

                text {
                  font-size: 32rpx;
                  color: #E1222A;
                }
              }
            }
          }
        }
      }

      .empty {
        width: 100%;
        height: 80vh;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }

  .bottom {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 168rpx;
    position: fixed;
    bottom: 0;
    left: 0;
    padding: 0 30rpx;
    background-color: #fff;
    z-index: 99;
    box-sizing: border-box;

    .total {
      display: flex;
      align-items: center;
      flex: 1;
      margin-left: 54rpx;

      text {
        font-size: 32rpx;
        color: #232323;
      }

      .price {
        font-size: 40rpx;
        color: #E1222A;
      }
    }

    .btn {
      width: 204rpx;
      height: 80rpx;
      font-size: 30rpx;
      color: #FFFFFF;
      line-height: 80rpx;
      text-align: center;
      background: #FC2F27;
      border-radius: 40rpx;
    }
  }
}

.radio {
  display: flex;
  align-items: center;
}
</style>